package com.de.Realm;

import com.de.pojo.AdminAccount;
import com.de.pojo.SysPermission;
import com.de.pojo.SysRole;
import com.de.service.AdminAccountService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @Description 登录realm
 * @Date 2020/2/26
 * @Author
 * @Version
 **/
public class LoginRealm extends AuthorizingRealm {

    private AdminAccountService adminAccountService;
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String account =(String) token.getPrincipal();
        Object credentials = token.getCredentials();
        AdminAccount admin = new AdminAccount(account,credentials.toString());
        AdminAccount ladmin = new AdminAccount();
        ladmin.setAccount("admin");
        ladmin.setPassword("123456");
        if (!ladmin.getAccount().equals(admin.getAccount())) {
            System.out.println("用户不存在");
        }
        //如果存在
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(ladmin,ladmin.getPassword()
        , ByteSource.Util.bytes(ladmin.getAccount()),getName());
        return authenticationInfo;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String account = (String)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        AdminAccount adminByAccount = adminAccountService.findAdminByAccount(account);
        for (SysRole role : adminByAccount.getRoles()) {
            authorizationInfo.addRole(role.getRoleName());
            for (SysPermission permission : role.getPermissions()) {
                authorizationInfo.addStringPermission(permission.getPermissionNme());
            }
        }
        return authorizationInfo;
    }
}
